import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import Qt.labs.qmlmodels 1.0
import FluentUI 1.0
import QtQuick.Templates 2.15 as T

T.ComboBox {
    id: control
    property var treeDataSource: []
    property var treeColumnSource: [{
            "dataIndex": "name",
            "title": "名称"
        }]
    property int popupHeight: 400 // 固定下拉框高度
    property bool showSearchBox: false // 默认不显示搜索框
    property bool showHeader: false // 默认不显示标题
    property bool showCheckBoxes: false
    property bool showFooter: false // 默认不显示底部状态栏

    // 添加当前选中项属性
    property var currentItem: null
    signal itemSelected(var itemData)

    implicitHeight: 36
    implicitWidth: 240
    editable: false
    font: FluTextStyle.Body

    // 自定义内容显示
    contentItem: FluText {
        text: currentItem ? currentItem.name : ""
        verticalAlignment: Text.AlignVCenter
        leftPadding: 10
        elide: Text.ElideRight
        color: {
            if (control.disabled) {
                return FluTheme.dark ? Qt.rgba(131 / 255, 131 / 255, 131 / 255, 1) : Qt.rgba(160 / 255, 160 / 255, 160 / 255, 1)
            }
            return FluTheme.dark ? Qt.rgba(1, 1, 1, 1) : Qt.rgba(0, 0, 0, 1)
        }
    }

    // 自定义指示器（下拉箭头）
    indicator: FluIcon {
        x: control.mirrored ? control.padding : control.width - width - control.padding
        y: control.topPadding + (control.availableHeight - height) / 2
        width: 20
        iconSource: FluentIcons.ChevronDown
        iconSize: 12
        opacity: enabled ? 1 : 0.3
    }

    // 自定义背景
    background: Rectangle {
        implicitWidth: 140
        implicitHeight: 32
        border.color: FluTheme.dark ? "#505050" : "#DFDFDF"
        border.width: control.visualFocus ? 2 : 1
        radius: 4
        color: {
            if (control.disabled) {
                return FluTheme.dark ? Qt.rgba(59 / 255, 59 / 255, 59 / 255, 1) : Qt.rgba(252 / 255, 252 / 255, 252 / 255, 1)
            }
            return control.hovered ? (FluTheme.dark ? Qt.rgba(
                                                          68 / 255, 68 / 255,
                                                          68 / 255, 1) : Qt.rgba(251 / 255, 251 / 255, 251
                                                                                 / 255, 1)) : (FluTheme.dark ? Qt.rgba(62 / 255,
                                                                                                                       62 / 255, 62 / 255,
                                                                                                                       1) : Qt.rgba(254 / 255, 254 / 255, 254 / 255, 1))
        }

        FluFocusRectangle {
            visible: control.visualFocus
            radius: 4
        }
    }

    // 自定义弹出窗口 - 使用固定高度
    popup: T.Popup {
        id: treePopup
        y: control.height + 4
        width: control.width
        height: control.popupHeight // 使用固定高度
        padding: 1

        enter: Transition {
            NumberAnimation {
                property: "opacity"
                from: 0
                to: 1
                duration: 120
            }
        }

        exit: Transition {
            NumberAnimation {
                property: "opacity"
                from: 1
                to: 0
                duration: 120
            }
        }

        background: Rectangle {
            radius: 5
            color: FluTheme.dark ? Qt.rgba(43 / 255, 43 / 255, 43 / 255, 1) : Qt.rgba(1, 1, 1, 1)
            border.color: FluTheme.dark ? Qt.rgba(26 / 255, 26 / 255, 26 / 255, 1) : Qt.rgba(191 / 255, 191 / 255, 191 / 255, 1)
            FluShadow {
                radius: 5
            }
        }

        contentItem: ColumnLayout {
            id: popupLayout
            spacing: 0

            // 搜索框 - 默认隐藏
            Rectangle {
                id: searchBox
                Layout.fillWidth: true
                height: showSearchBox ? 42 : 0
                visible: showSearchBox
                color: FluTheme.dark ? Qt.rgba(50 / 255, 50 / 255, 50 / 255, 1) : Qt.rgba(247 / 255, 247 / 255, 247 / 255, 1)

                FluTextBox {
                    id: searchInput
                    anchors {
                        left: parent.left
                        right: clearButton.left
                        verticalCenter: parent.verticalCenter
                        leftMargin: 8
                        rightMargin: 5
                    }
                    placeholderText: "搜索..."

                    onTextChanged: {
                        treeView.filterText = text.toLowerCase()
                    }
                }

                FluIconButton {
                    id: clearButton
                    anchors {
                        right: parent.right
                        verticalCenter: parent.verticalCenter
                        rightMargin: 8
                    }
                    width: 30
                    height: 30
                    iconSource: FluentIcons.ChromeClose
                    iconSize: 10
                    visible: searchInput.text !== ""

                    onClicked: {
                        searchInput.text = ""
                    }
                }
            }

            // 标题栏 - 默认隐藏
            Rectangle {
                id: headerBar
                Layout.fillWidth: true
                height: showHeader ? 36 : 0
                visible: showHeader
                color: FluTheme.dark ? Qt.rgba(50 / 255, 50 / 255, 50 / 255, 1) : Qt.rgba(247 / 255, 247 / 255, 247 / 255, 1)

                Row {
                    anchors.fill: parent
                    spacing: 1

                    Repeater {
                        model: control.treeColumnSource

                        Rectangle {
                            width: modelData.width || 200
                            height: parent.height
                            color: "transparent"

                            FluText {
                                anchors.centerIn: parent
                                text: modelData.title
                                font: FluTextStyle.Caption
                            }
                        }
                    }
                }
            }

            // TreeView容器 - 使用固定高度
            Item {
                id: treeContent
                Layout.fillWidth: true
                Layout.fillHeight: true // 填充剩余空间
                clip: true

                EnhancedTreeView {
                    id: treeView
                    anchors.fill: parent
                    dataSource: control.treeDataSource
                    columnSource: control.treeColumnSource
                    headerVisible: false
                    showLine: false
                    cellHeight: 30
                    depthPadding: 12
                    checkable: control.showCheckBoxes
                    borderColor: FluTheme.dark ? Qt.rgba(55 / 255, 55 / 255, 55 / 255,
                                                         1) : Qt.rgba(228 / 255, 228 / 255, 228 / 255, 1)

                    property string filterText: ""

                    // 当用户点击树节点时处理
                    onCurrentChanged: {
                        if (current) {
                            var itemData = current.data
                            control.currentItem = itemData
                            control.itemSelected(itemData)
                            treePopup.close()
                        }
                    }

                    // 自定义过滤逻辑
                    function filterAcceptsRow(rowModel) {
                        if (filterText === "")
                            return true

                        // 检查当前节点是否匹配
                        if (rowModel.data.name.toLowerCase().includes(filterText)) {
                            return true
                        }

                        // 检查子节点是否匹配
                        for (var i = 0; i < rowModel.children.length; i++) {
                            if (filterAcceptsRow(rowModel.children[i])) {
                                return true
                            }
                        }

                        return false
                    }

                    // 过滤函数
                    function filterRow(rowModel) {
                        if (!filterAcceptsRow(rowModel)) {
                            return false
                        }

                        // 展开匹配的节点
                        rowModel.isExpanded = true

                        // 过滤子节点
                        var visibleChildren = []
                        for (var i = 0; i < rowModel.children.length; i++) {
                            if (filterAcceptsRow(rowModel.children[i])) {
                                visibleChildren.push(rowModel.children[i])
                                filterRow(rowModel.children[i])
                            }
                        }
                        rowModel.children = visibleChildren

                        return true
                    }

                    // 应用过滤
                    function applyFilter() {
                        if (filterText === "") {
                            tree_model.setDataSource(control.treeDataSource)
                            return
                        }

                        var filteredData = []
                        for (var i = 0; i < control.treeDataSource.length; i++) {
                            var root = JSON.parse(JSON.stringify(control.treeDataSource[i]))
                            if (filterRow(root)) {
                                filteredData.push(root)
                            }
                        }

                        tree_model.setDataSource(filteredData)
                    }

                    onFilterTextChanged: {
                        applyFilter()
                    }
                }
            }

            // 底部状态栏 - 默认隐藏
            Rectangle {
                Layout.fillWidth: true
                height: showFooter ? 24 : 0
                visible: showFooter
                color: FluTheme.dark ? Qt.rgba(50 / 255, 50 / 255, 50 / 255, 1) : Qt.rgba(247 / 255, 247 / 255, 247 / 255, 1)
                border.color: FluTheme.dark ? Qt.rgba(55 / 255, 55 / 255, 55 / 255,
                                                      1) : Qt.rgba(228 / 255, 228 / 255, 228 / 255, 1)
                border.width: 1

                FluText {
                    anchors.centerIn: parent
                    text: treeView.count() + " 个项目"
                    color: FluTheme.dark ? FluColors.Grey110 : FluColors.Grey130
                    font: FluTextStyle.Caption
                }
            }
        }
    }

    // 初始化TreeView数据
    Component.onCompleted: {
        if (treeDataSource.length > 0) {
            // 设置默认选中项
            currentItem = treeDataSource[0]
        }
    }
}
